package com.cnplan.controller.auth;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cnplan.auth.utils.PasswordUtils;
import com.cnplan.core.Constant;
import com.cnplan.core.MyUtils;
import com.cnplan.core.ResultGenerator;
import com.cnplan.entity.SystemRole;
import com.cnplan.entity.SystemUser;
import com.cnplan.service.AuthService;
import com.cnplan.vo.SystemRoleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/27.
 */
@Controller
@RequestMapping("/auth/user")
public class UserController {

    @Autowired
    private AuthService authService;

    // list user
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public String list(Integer pageIndex, Integer pageSize, String keyword, Model model, HttpServletRequest request){
        if(pageIndex==null || pageIndex<1){
            pageIndex= 1;
        }
        if(pageSize==null || pageSize<0){
            pageSize = Constant.PAGE_SIZE;
        }

        PageHelper.startPage(pageIndex, pageSize);
        List<SystemUser> systemUserList = authService.listSystemUser(new EntityWrapper<SystemUser>(), keyword);
        PageInfo<SystemUser> pageInfo = new PageInfo<SystemUser>(systemUserList);

        model.addAttribute("title", "用户");
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("keyword", keyword);
        model.addAttribute("recordList", systemUserList);

        return "auth/user/list";
    }

    // list user (post)
    @RequestMapping(value = {"/list"}, method = RequestMethod.POST)
    public String listPost(String keyword, Model model, HttpServletRequest request){
        keyword = MyUtils.formatKeyword(keyword);

        model.addAttribute("title", "用户");
        model.addAttribute("keyword", keyword);

        return "redirect:" + request.getServletPath();
    }

    // create user
    @RequestMapping(value = {"/create"}, method = RequestMethod.POST)
    @ResponseBody
    public String createPost(ServletRequest request){
        Gson gson = new Gson();
        try{
            SystemUser systemUser = new SystemUser();
            // 设置默认值
            systemUser.setUserName("User_" + System.currentTimeMillis());
            systemUser.setUserPassword(Constant.DEFAULT_PASSWORD);
            systemUser.setActive(true);

            PasswordUtils.encryptPassword(systemUser);

            return gson.toJson(authService.insertSystemUser(systemUser));
        }catch (Exception e){
            return gson.toJson(ResultGenerator.genFailResult("新增用户异常 => " + e.getMessage()));
        }
    }

    // update user
    @RequestMapping(value = {"/update/{id}"}, method = RequestMethod.GET)
    public String update(@PathVariable("id") Long id, Model model){
        SystemUser tempUser = new SystemUser();
        tempUser.setId(id);
        SystemUser systemUser = authService.getSystemUser(tempUser);

        // 获取用户角色
        List<SystemRoleVO> systemRoleVOList = new ArrayList<SystemRoleVO>();
        EntityWrapper<SystemRole> ew = new EntityWrapper<SystemRole>();
        List<SystemRole> systemRoleList = authService.listSystemRole(ew);
        List<SystemRole> userRoleList = authService.listRoleByUserId(id);
        for(SystemRole systemRole : systemRoleList){
            SystemRoleVO systemRoleVO = new SystemRoleVO();
            systemRoleVO.setId(systemRole.getId());
            systemRoleVO.setRoleName(systemRole.getRoleName());
            systemRoleVO.setRoleDesc(systemRole.getRoleDesc());
            systemRoleVO.setDisplayOrder(systemRole.getDisplayOrder());

            Boolean hasRole = false;
            for(SystemRole userRole : userRoleList){
                if(userRole.getId().equals(systemRole.getId())){
                    hasRole = true;
                    break;
                }
            }
            systemRoleVO.setSelected(hasRole);
            systemRoleVOList.add(systemRoleVO);
        }

        // 返回数据
        model.addAttribute("title", "用户");
        model.addAttribute("record", systemUser);
        model.addAttribute("roleList", systemRoleVOList);
        return "auth/user/update";
    }

    // update user (post)
    @RequestMapping(value = {"/update"}, method = RequestMethod.POST)
    @ResponseBody
    public String updatePost(SystemUser systemUser, String userRole){
        Gson gson = new Gson();
        try{
            // 设定用户角色
            if(userRole == null){
                Long[] longArray = new Long[0];
                authService.resetUserRoles(systemUser.getId(), longArray);
            }else{
                String[] stringArray = userRole.split(",");
                Long[] longArray = new Long[stringArray.length];
                for(int i=0, length = stringArray.length; i<length; i++){
                    longArray[i] = Long.valueOf(stringArray[i]);
                }
                authService.resetUserRoles(systemUser.getId(), longArray);
            }
            return gson.toJson(authService.updateSystemUser(systemUser));
        } catch (Exception e){
            return gson.toJson(ResultGenerator.genFailResult("更新用户异常 => " + e.getMessage()));
        }
    }

    // delete user (post)
    @RequestMapping(value = {"/delete"}, method = RequestMethod.POST)
    @ResponseBody
    public String deletePost(Long id) {
        Gson gson = new Gson();
        try {
            return gson.toJson(authService.deleteSystemUser(id));
        } catch (Exception e) {
            return gson.toJson(ResultGenerator.genFailResult("删除用户异常 => " + e.getMessage()));
        }
    }

    // reset user password (post)
    @RequestMapping(value = {"/resetPassword"}, method = RequestMethod.POST)
    @ResponseBody
    public String resetPassword(Long id) {
        Gson gson = new Gson();
        try {
            return gson.toJson(authService.modifyPassword(Constant.RESET_PASSWORD, id, null, Constant.DEFAULT_PASSWORD));
        } catch (Exception e) {
            return gson.toJson(ResultGenerator.genFailResult("重置用户密码异常 => " + e.getMessage()));
        }
    }

    // change user password (post)
    @RequestMapping(value = {"/changePassword"}, method = RequestMethod.POST)
    @ResponseBody
    public String changePassword(Long id, String oriPwd, String newPwd, ServletRequest request) {
        Gson gson = new Gson();
        // 判断是否为当前用户
        String user_id = ((HttpServletRequest) request).getSession().getAttribute(Constant.CURRENT_USER_ID).toString();
        if(user_id.equals(id.toString())){
            try{
                return gson.toJson(authService.modifyPassword(Constant.CHANGE_PASSWORD, id, oriPwd, newPwd));
            } catch (Exception e){
                return gson.toJson(ResultGenerator.genFailResult("修改密码异常 => " + e.getMessage()));
            }
        } else {
            return gson.toJson(ResultGenerator.genFailResult("只有本人才可以修改登录密码"));
        }
    }

    // manage user information
    @RequestMapping(value = {"/manage/{id}"}, method = RequestMethod.GET)
    public String manage(@PathVariable("id") Long id, Model model){
        SystemUser tempUser = new SystemUser();
        tempUser.setId(id);
        SystemUser systemUser = authService.getSystemUser(tempUser);

        model.addAttribute("title", "用户");
        model.addAttribute("record", systemUser);
        model.addAttribute("title", "个人信息");
        return "auth/user/manage";
    }

    // update user (post)
    @RequestMapping(value = {"/manage"}, method = RequestMethod.POST)
    @ResponseBody
    public String managePost(SystemUser systemUser, ServletRequest request){
        Gson gson = new Gson();

        // 判断是否为当前用户
        String user_id = ((HttpServletRequest) request).getSession().getAttribute(Constant.CURRENT_USER_ID).toString();
        if(user_id.equals(systemUser.getId().toString())){
            try{
                return gson.toJson(authService.updateSystemUser(systemUser));
            } catch (Exception e){
                return gson.toJson(ResultGenerator.genFailResult("编辑个人信息异常 => " + e.getMessage()));
            }
        } else {
            return gson.toJson(ResultGenerator.genFailResult("只有本人才可以编辑个人信息"));
        }

    }
}
